$(function(){

    //底部定位

    $('body').css('min-height',$(window).height()-306 + 'px');

	// 返回顶部
    function ifHide(){
        var h = 400;
        var scr_top = $(document).scrollTop();
        if(scr_top > h){
            $('#backTop').show();
        }else{
            $('#backTop').hide();
        }
    }
    ifHide();

    $(window).scroll(function(e){
        ifHide();
    });  

    $('#backTop').click(function(){
        if(!$('html,body').is(':animated')){
            $('html,body').animate({
                scrollTop: '0px'
            }, 100);
        };	
    });

    //帮我找货
    var act_text = "请尽可能详细写下您所需钢材的需求，方便我们为您更快找到合适货源！";

	$('#description').focus(function(){
        if($(this).val() == act_text){
            $(this).val("").css('color','#999');
        }
    });
    $('#description').blur(function(){
        if($(this).val() == ""){
        	$(this).val(act_text).css('color','#b5b5b6');
        }
    });

    //意见反馈

    $('.pos-l-bg ul li.user').click(function(){
        $('.popup').show();
        $('.popup-feedback').show();
    });
    
    var feedback_text = "请留下您的意见和建议";

    $('#feedback_text').focus(function(){
        if($(this).val() == feedback_text){
            $(this).val("").css('color','#999');
        }
    });
    $('#feedback_text').blur(function(){
        if($(this).val() == ""){
            $(this).val(feedback_text).css('color','#b5b5b6');
        }
    });

    //优质资源

    for (var i = 0; i < $('.resour-box .info-box').length; i++) {
        if(i<3){
            $('.resour-box .info-box').eq(i).css('border-top','none');
        }
        $('.resour-box .info-box').eq(i*3+2).css('border-right','none');
    };
	
    //index_ banner 找货切换
    $('.banner .search-box .box-left ul li').hover(function(){
    	var index = $(this).index();
    	$(this).addClass('active').siblings().removeClass('active');
    	$('.banner .search-box .box-right .box').hide().eq(index).show();
    });

    //index_ banner 找货AJAX

    var $search_input = $('.search-box .box-right [type="text"].form-control');

    $search_input.after('<div class="info-ul"><ul></ul></div>');
    $search_input.focus(function(e){
        var str = "";
        var type_name = $(this).attr('name');
        var $this = $(this);
        e?e.stopPropagation():event.cancelBubble = true;
        if (type_name) {
             if(type_name != 'spec'){
                $.ajax({
                    url: "/shop_select",
                    type: "POST",
                    data: 'type_name='+type_name,
                    success: function (msg) {
                        if(msg){
                            $.each(msg,function(index,arr){
                                if(type_name == "city_name"){
                                    str += "<li><a href=\"javascript:;\" rel="+arr.city_name+">"+arr.city_name+"</a></li>";
                                }else if(type_name == "storage_name"){
                                    str += "<li><a href=\"javascript:;\" rel="+arr.storage_id+">"+arr.storage_name+"</a></li>";
                                }else if(type_name == "brand_name"){
                                    str += "<li><a href=\"javascript:;\" rel="+arr.brand_id+">"+arr.brand_name+"</a></li>";
                                }else if(type_name == "material_name"){
                                    str += "<li><a href=\"javascript:;\" rel="+arr.m_id+">"+arr.m_name+"</a></li>";
                                }else if(type_name == "factory_name"){
                                    str += "<li><a href=\"javascript:;\" rel="+arr.factory_id+">"+arr.factory_name+"</a></li>";
                                };
                            });
                            $this.siblings(".info-ul").show().children().html(str);
                        }
                    }
                });
            };
        };
           

    });

    $('.search-box .box-right .info-ul').blur(function(e){
        e?e.stopPropagation():event.cancelBubble = true;
    });

    $(document).click(function() {
        $('.search-box .box-right .info-ul').hide();
    });

    $(document).delegate('.search-box .box-right .info-ul li a','click',function(){
        var a_name = $(this).html();
        var a_id = $(this).attr('rel');
        $(this).parents('.form-group').find('input').val(a_name);
        $(this).parents('.form-group').find('input[type="hidden"]').val(a_id);
        $(this).parents('.form-group').find('.info-ul').hide();
    });

    //index_文字滚动
    
    var nowDate = new Date();
    var modifyDate = '';
        modifyDate += nowDate.getFullYear() + '-';    
        modifyDate += whether_ten(nowDate.getMonth()+1) + '-';       
        modifyDate += whether_ten(nowDate.getDate()) + ' ';
        modifyDate += whether_ten(nowDate.getHours()) + ':';
    var modifyDateMin = [];

    for (var i = 0; i < $('#info-ul li').length; i++) {
        var min = nowDate.getMinutes()-Math.floor(Math.random()*10);
        if (min>=0) {
            modifyDateMin[i] = whether_ten(min);
        }else{
            modifyDateMin[i] = 00;
        };
        $('#info-ul li').eq(i).find('div.left').eq(1).html(modifyDate+modifyDateMin[i]);
    };

    function whether_ten(number){
        if (number<10) {
            return "0"+number;
        }else{
            return number;
        };
    }

    //背景幕——登录 / popup-show

    $(document).delegate('.login-close','click',function(){
        $('.popup').hide();
        $('.popup-login').hide();
    });

    $(document).delegate('.popup','click',function(){
        $('.popup').hide();
        $('.popup-login').hide();
        $('.popup-show').hide();
        $('.popup-feedback').hide();
    });

    $(document).delegate('.popup-close','click',function(){
        $('.popup').hide();
        $('.popup-show').hide();
    });

    $(document).delegate('.popup-show .close','click',function(){
        $('.popup').hide();
        $('.popup-show').hide();
    });

    //index_pos_购物车

    $('.shop-in .in-ul').css('height',$(window).height()-160 + 'px');

    $(window).resize(function(){
       $('.shop-in .in-ul').css('height',$(window).height()-160 + 'px');
    });

    $('.pos-right').click(function(e){
        e?e.stopPropagation():event.cancelBubble = true;
    });

    $('.addcar').click(function(e){
        //e?e.stopPropagation():event.cancelBubble = true;
    });

    $('#shopping').click(function(e){
        e?e.stopPropagation():event.cancelBubble = true;
        if (!$(this).hasClass('open')) {
            $(this).addClass('open');
            $('.pos-right').animate({
                'right':'0'
            },300);
        }else{
            $(this).removeClass('open');
            $('.pos-right').animate({
                'right':'-280px'
            },300);
        };     
    });

    $('.shop-in .in-head i').click(function(){
        $('#shopping').removeClass('open');
        $('.pos-right').animate({
            'right':'-280px'
        },300);
    });

    $(document).click(function(){
        $('#shopping').removeClass('open');
        $('.pos-right').animate({
            'right':'-280px'
        },300);
    });

    //index_pos_购物车全选

    $('#check-all').click(function(){
        var checked_status = this.checked;
        $(this).parents('.shop-in').find('input[type="checkbox"]').each(function () {
            this.checked = checked_status;
        });
        //个人主页全选
        $(this).parents('.home-bot').find('input.res-check').each(function () {
            this.checked = checked_status;
        });
    });

    $('.check-all').click(function(){
        var checked_status = this.checked;
        //购物车
        $(this).parents('.table').find('input[type="checkbox"]').each(function () {
            this.checked = checked_status;
        });
    });

    $('.check-bus').click(function(){
        var checked_status = this.checked;
        $(this).parents('.in-li').find('input[type="checkbox"]').each(function () {
            this.checked = checked_status;
        });
        //购物车
        $(this).parents('tbody').find('input[type="checkbox"]').each(function () {
            this.checked = checked_status;
        });
    });

    var $checkbox = $('input[type="checkbox"]');
    var cart = [];
    var cart_submit = "/shop_cart_submit?cart_id=";

    for (var i = 0; i < $checkbox.length; i++) {
        if (typeof($checkbox.eq(i).attr('cart-id')) != 'undefined') {
            if($checkbox[i].checked){
                cart.push($checkbox.eq(i).attr('cart-id'));
            };
        }
    };
    $.each(cart,function(index,arr){
        cart_submit += arr+',';
    });
    $('#cart-submit').attr('href',cart_submit);
    
    $('input[type="checkbox"]').click(function(){
        if (!$(this).is(':checked')) {
            $('#check-all').attr("checked",false);
            $(this).parents('.in-li').find('.check-bus').attr("checked",false);
            //购物车
            $('.check-all').attr("checked",false);
            $(this).parents('tbody').find('.check-bus').attr("checked",false);
        }

        cart = [];
        var cart_submit = "/shop_cart_submit?cart_id=";
        
        for (var i = 0; i < $checkbox.length; i++) {
            if (typeof($checkbox.eq(i).attr('cart-id')) != 'undefined') {
                if($checkbox[i].checked){
                    cart.push($checkbox.eq(i).attr('cart-id'));
                };
            }
        };
        $.each(cart,function(index,arr){
            cart_submit += arr+',';
        });
        $('#cart-submit').attr('href',cart_submit);
        statistical_info();
    });

    //index_pos_购物车数量

    $('.info-num').append('<span></span>');

    $(".info-num input").blur(function(){
        var numVal = $(this).val();
        var product_id = $(this).attr("product_id");
        var $this = $(this);
        
        statistical_num(numVal,product_id,$this);
        statistical_info();
    });

    $('.info-num .pre').click(function(){
        var numVal = parseInt($(this).siblings('input').val()-1);
        var product_id = $(this).siblings('input').attr("product_id");
        var $this = $(this);
        
        statistical_num(numVal,product_id,$this);
        statistical_info();
    });

    $('.info-num .next').click(function(){
        var numVal = parseInt($(this).siblings('input').val())+1;
        var product_id = $(this).siblings('input').attr("product_id");
        var $this = $(this);

        statistical_num(numVal,product_id,$this);
        statistical_info();
    });

    function ajax_number(numVal,product_id,$this){
        $.ajax({
            url: "/shop_update_cart",
            type: "POST",
            data: 'down_num='+numVal+'&product_id='+product_id,
            async:false,
            success: function (msg) {
                if(msg==1){
                    $this.siblings('span').hide();
                }
            }
        });
    }

    function statistical_num(numVal,product_id,$this){

        var stock = parseInt($this.parents('.info').attr('stock'));
        var price = parseInt($this.parents('.info').find('.price').html().substring(1));
        var w_per_piece = parseFloat($this.parents('.info').find('.w_per_piece').html());

        if((/^(\+|-)?\d+$/.test( numVal ))&&numVal>0){ 
            if(numVal > stock){
                if ($this.hasClass('number')) {
                    $this.val(stock);
                };
                $this.siblings('span').show().html('最多可购买'+stock+'件');
                $this.parents('.info').find('.total').html("<span>￥"+(price*w_per_piece*stock).toFixed(2)+"</span>");
            }else{
                if (!$this.hasClass('number')) {
                    $this.siblings('input').val(numVal);
                };
                $this.parents('.info').find('.total').html("<span>￥"+(price*w_per_piece*numVal).toFixed(2)+"</span>");
                ajax_number(numVal,product_id,$this);
                $this.siblings('span').hide();
            }
        }else{
            $this.siblings('span').show().html('数量中请输入正整数！');
            $this.val(1);
            $this.parents('.info').find('.total').html("<span>￥"+price.toFixed(2)+"</span>");
        }   

    }

    function statistical_info(numVal){
        var NUMVAL = [],W_PER = [],TOTAL = [];

        for (var i = 0; i < $checkbox.length; i++) {
            if (typeof($checkbox.eq(i).attr('cart-id')) != 'undefined') {
                var numVal = arguments[0] ? arguments[0] : $checkbox.eq(i).parents('.info').find('.number').val();
                var w_per_piece = parseFloat($checkbox.eq(i).parents('.info').find('.w_per_piece').html());
                var price = parseInt($checkbox.eq(i).parents('.info').find('.price').html().substring(1));
                if($checkbox[i].checked){
                    NUMVAL.push(numVal);
                    W_PER.push(numVal*w_per_piece);
                    TOTAL.push(numVal*w_per_piece*price);
                };
            }
        };

        if (NUMVAL.length == 0 && W_PER.length == 0 && TOTAL.length == 0 ) {
            $('.sta-num').html("商品重量小计：共 <span>0</span> 件 0.0000吨");
            $('.sta-mon').html("商品总金额（不含运费）: <span>￥0.00</span>");
            $('.in-bot .sta-num').html("共 <span>0</span> 件");
            $('.in-bot .sta-mon').html("商品总计：<span>￥0.00</span>");
        }else{
            $('.sta-num').html("商品重量小计：共 <span>"+eval(NUMVAL.join("+"))+"</span> 件 "+eval(W_PER.join("+")).toFixed(4)+"吨");
            $('.sta-mon').html("商品总金额（不含运费）: <span>￥"+eval(TOTAL.join("+")).toFixed(2)+"</span>");
            $('.in-bot .sta-num').html("共 <span>"+eval(NUMVAL.join("+"))+"</span> 件");
            $('.in-bot .sta-mon').html("商品总计：<span>￥"+eval(TOTAL.join("+")).toFixed(2)+"</span>");
        };  
    }

    //资源单

    $(document).delegate('.res-conf dl a','click',function(){
        $(this).parents('dl').find('a').removeClass('active');
        $(this).addClass('active');

        if($(this).parents('dl').hasClass('first')){
            $('#city').val($(this).html());
        }else{
            $('#category').val($(this).html());
        }
    });

    //个人中心资源单关注

    var cancel = '';
        cancel = '<div class=\"cancel-p\">';
        cancel +='<i><img src=\"./resource/img/gl_show_err.png\" alt=""></i>';
        cancel +='<div class=\"left\">';           
        cancel +='是否取消关注此资源单？<br/>';                 
        cancel +='<div class="btn"><a href="javascript:;" class="deter">确定</a>';
        cancel +='<a href="javascript:;" class="close">取消</a></div>';                 
        cancel +='</div><div class=\"cancel-close\"></div></div>';   
    var succ = '';
        succ = '<div class=\"succ-p\">';
        succ +='<i><img src=\"./resource/img/gl_show_succ.png\" alt=""></i>';
        succ +='<div class=\"left\">';           
        succ +='关注成功<br/>';                 
        succ +='<span>您可以<a href=\"/user_person\">去看看</a>关注的资源单</span>';
        succ +='</div><div class=\"succ-close\"></div></div>';

    $('.home-bot .Follow').after('<div class="follow-cancel"></div><div class="follow-succ"></div>');

    $(document).delegate('.home-bot .Follow','click',function(){

        var product_id = $(this).attr('product_id');

        $('.follow-succ').html(succ);
        $('.follow-cancel').html(cancel);
        if ($(this).hasClass('succ')) {
            $(this).siblings('.follow-cancel ').find('.deter').attr('product_id',product_id);
            $('.follow-cancel').hide();
            $(this).siblings('.follow-cancel').show();
            $('.follow-succ').hide();
        }else{
            var $this = $(this);
            $.ajax({
                url: "/follow_add",
                type: "get",
                data: "product_id=" + product_id,
                success: function (msg) {
                   if(msg){
                       $this.addClass('succ').html('取消关注');
                       $this.siblings('.follow-succ').show();
                       $('.follow-cancel').hide();
                   }
                }
            })
        };
    });

    $(document).delegate('.home-bot .follow-cancel .deter','click',function(){

        var product_id = $(this).attr('product_id');
        var $this = $(this);
        var page = $('ul.pagination li.active a').html();

        $.ajax({
            url: "/follow_delete",
            type: "get",
            data: "product_id=" + product_id,
            success: function (msg) {
                if(msg){
                    $.ajax({
                        url: "/ajax_user_follow",
                        type: "get",
                        data: 'product_id='+product_id,
                        async:false,
                        success: function (msg) {
                            window.location.href="http://www.ganglian.com/user_person?page="+page;
                            if($('.home-bot tbody tr').length == 1){
                                window.location.href="http://www.ganglian.com/user_person?page="+(page-1);
                            }
                            $('#follow_list').html(msg);
                        }
                    });
                }
            }
        })

    });

    $(document).delegate('.follow-cancel .close','click',function(){
        $('.follow-cancel').hide();
    });

    $(document).delegate('.cancel-close','click',function(){
        $('.follow-cancel').hide();
    });

    $(document).delegate('.succ-close','click',function(){
        $('.follow-succ').hide();
    });

    //关注资源单

    $('.res-cont .Follow').append('<div class="follow-cancel"></div><div class="follow-succ"></div>');

    $(document).delegate('.res-cont .Follow a.a','click',function(){

        var product_id = $(this).parents('.Follow').attr('product-id');

        $('.follow-succ').html(succ);
        $('.follow-cancel').html(cancel);
        if ($(this).hasClass('succ')) {
            $(this).siblings('.follow-cancel ').find('.deter').attr('product-id',product_id);
            $('.follow-cancel').hide();
            $(this).siblings('.follow-cancel').show();
            $('.follow-succ').hide();
        }else{
            var $this = $(this);
            $.ajax({
                url: "/follow_add",
                type: "get",
                data: "product_id=" + product_id,
                success: function (msg) {
                   if(msg){
                       $this.addClass('succ').html('已关注');
                       $('.follow-succ').hide();
                       $this.siblings('.follow-succ').show();
                       $('.follow-cancel').hide();
                   }
                }
            })
        };
    });

    $(document).delegate('.res-cont .follow-cancel .deter','click',function(){

        var product_id = $(this).attr('product-id');
        var $this = $(this);

        $.ajax({
            url: "/follow_delete",
            type: "get",
            data: "product_id=" + product_id,
            success: function (msg) {
                if(msg){
                   $this.parents('.Follow').find('.a').removeClass('succ').html('关注');
                   $('.follow-cancel').hide();
                   $('.follow-succ').hide();
                }
            }
        })

    });

    //资源单描述

    $('.describe').click(function(){
        if (!$(this).hasClass('open')) {
            $(this).addClass('open');
        }else{
            $(this).removeClass('open');
        };
    });

    //消息通知 切换

    $(document).delegate('.news-ul li','click',function(){
        var index = $(this).index();
        $(this).addClass('active').siblings().removeClass('active');
        $('.news-cont .cont').hide().eq(index).show();
    });

    //提交订单 qiehuan

    $('.shopping-submit .ul-pay li').click(function(){
        $(this).addClass('active').siblings().removeClass('active');
    });

    //立即开票

    $('.billing').click(function(e){
        e?e.stopPropagation():event.cancelBubble = true;
        $('.popup-billing').show();
        $('.popup').show();
    });
    $('.popup-billing .close').click(function(){
        $('.popup-billing').hide();
        $('.popup').hide();
    });
    $('.popup-billing').click(function(e){
        e?e.stopPropagation():event.cancelBubble = true;
    });
    $(document).click(function() {
        $('.popup-billing').hide();
    });

    //上传资源单 -- xls

    $('#file_ex').change(function(){
        var file = $(this).get(0).files[0];
        var f_content = $(this).val();
        var fileext=f_content.substring(f_content.lastIndexOf("."),f_content.length);
        fileext=fileext.toLowerCase();
        if (fileext!='.xls'&&fileext!='.xlsx'){  
            alert("对不起，导入数据格式必须是xls格式或者xlsx格式文件哦，请您调整格式后重新上传，谢谢 ！");
        }else{
            $('#file_ex').parents('.file-ex').siblings('span').hide();
            if (window.applicationCache) {
                $('#file_ex').parents('.file-ex').siblings('.info').html("<br/><img src=\"./resource/img/xsl_icon.jpg\">"+file.name+"<a href=\"javascript:;\">下载资源单模板</a>");
            }else{
                $('#file_ex').parents('.file-ex').siblings('.info').html("<br/><img src=\"./resource/img/xsl_icon.jpg\">"+f_content+"<a href=\"javascript:;\">下载资源单模板</a>");
                $('#file_ex').parents('.file-ex').siblings('span').show().html('很抱歉，由于采用了HTML5，当前浏览器无法完美呈现该页面。');
            };
        }  
    });

    //分页居中

    var pageW = $('ul.pagination').width();
    var pageML = -pageW / 2 + 'px';
    $('ul.pagination').css({
        'left':'50%',
        'margin-left':pageML
    });

    //切换页面 高亮

    $('.nav li a').each(function(){
        if ($(this)[0].href == String(window.location)) {
            $(this).attr('href','javascript:void(0);').parent().addClass('active').siblings().removeClass('active');
        };
    });

    $('.user-ul li a').each(function(){
        if ($(this)[0].href == String(window.location)) {
            $('.user-ul li').removeClass('active');
            $(this).attr('href','javascript:void(0);').parent().addClass('active');
        };
    });

    $('.order-ul li a').each(function(){
        if ($(this)[0].href == String(window.location)) {
            $(this).attr('href','javascript:void(0);').parent().addClass('active').siblings().removeClass('active');
        };
    });

    $('.pro-ul li a').click(function(){
        var index = $(this).parents('li').attr('rel');

        $('.pro-ul li').removeClass('active');
        $(this).parent().addClass('active');
        $('.pro-cont .cont').hide().eq(index).show();
    });

});